package me.ereach.advanced.exceptions;

import org.junit.Test;

import java.io.FileReader;
import java.io.IOException;

public class MyTests {
    @Test
    public void testFile() {
        try {
            FileReader f = new FileReader("d:\\readme.txt");
            int read = 0;
            while (true) {
                read = f.read();
                if (read == -1)
                    break;
                System.out.print((char) read);
            }
            f.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void fileTest3() {
        StringBuffer sb = new StringBuffer();

        try (FileReader reader = new FileReader("/Users/jinzhengdong/readme.txt")) {
            int read = 0;
            while (true) {
                read = reader.read();
                if (read != -1) {
                    sb.append((char) read);
                }
                else
                    break;
            }
        }
        catch (IOException e) {
            System.out.println(e.getMessage());
        }

        System.out.println(sb.toString());
    }

    @Test
    public void fileTest2() {
        StringBuilder sb = new StringBuilder();

        try (FileReader reader = new FileReader("/Users/jinzhengdong/readme.txt")) {
            int read = 0;
            while (true) {
                read = reader.read();
                if (read != -1) {
                    sb.append((char) read);
                }
                else
                    break;
            }
        }
        catch (IOException e) {
            System.out.println(e.getMessage());
        }

        System.out.println(sb.toString());
    }

    @Test
    public void fielTest() {
        FileReader fileReader = null;
        StringBuilder sb = new StringBuilder();

        try {
            fileReader = new FileReader("/Users/jinzhengdong/readme.txt");
            int read = 0;
            while (true) {
                read = fileReader.read();
                if (read != -1) {
                    sb.append((char) read);
                }
                else
                    break;
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        finally {
            try {
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        System.out.println(sb.toString());
    }

    // 异常
    @Test
    public void showException() {
        sayHello("Tom");
        try {
            sayHello(null);
        }
        catch (NullPointerException ex) {
            System.out.println(ex.getMessage());
        }

    }

    private void sayHello(String name) {
        System.out.println("Hello, " + name.toUpperCase());
    }
}
